package com.iyang.bootredislock.service.impl;

import com.iyang.bootredislock.mapper.UserMapper;
import com.iyang.bootredislock.pojo.User;
import com.iyang.bootredislock.service.RedisLockService;
import com.iyang.bootredislock.utils.RedisDistributedLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;

/**
 *
 * @Author: Mu_YI
 * @Date: 2019/4/7 19:11
 * @Version 1.0
 */

@Service
public class RedisLockServiceImpl implements RedisLockService {

    @Autowired
    private UserMapper userMapper;

    /**
     * 测试redis分布式锁
     * @param id
     * @param stock
     */
    @Override
    public void updateStockById1(Long id, Long stock) {
        System.out.println("-----当前线程名称------>" + Thread.currentThread().getName());
        //随机值，确保唯一
        String randomValue = id + UUID.randomUUID().toString();
        // 加锁
        RedisDistributedLock.acquireLock(id.toString(),randomValue,5*1000);
        // 业务逻辑
        User user = userMapper.getById(id);
        Long age = user.getAge();
        age += stock;
        userMapper.updateAgeById(id,age);

        // 释放锁
        RedisDistributedLock.releaseLock(id.toString(),randomValue);
    }

    @Override
    public void updateNoLock(Long id, Long stock) {
        // 业务逻辑
        User user = userMapper.getById(id);
        Long age = user.getAge();
        System.out.println("---------------当前线程的名字-------->" + Thread.currentThread().getName() + ";age:" + age);
        age += stock;
        userMapper.updateAgeById(id,age);
    }

}
